import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { 
  Button, 
  Table, 
  Input, 
  Select, 
  Tabs, 
  Tag, 
  Pagination,
  Space,
  Typography,
  message,
  Spin,
  Tooltip
} from 'antd';
import { 
  SearchOutlined, 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  MinusCircleOutlined 
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { problemListApi } from '../../api/services/problemList';
import type { ProblemListItem, ProblemListRequest } from '../../api/dto/problemManagement';
import './index.less';

const { Title } = Typography;
const { Option } = Select;

// 常量定义
const CONSTANTS = {
  DIFFICULTY_MAP: {
    1: '简单',
    2: '中等', 
    3: '困难'
  },
  
  STATUS_MAP: {
    1: '通过',
    2: '未通过',
    3: '未尝试'
  },
  
  TAB_ITEMS: [
    { key: 'all', label: '全部题目' },
    { key: 'c', label: 'C语言' },
    { key: 'cpp', label: 'C++' },
    { key: 'data-structure', label: '数据结构' },
    { key: 'algorithm', label: '算法' },
    { key: 'database', label: '数据库' },
    { key: 'shell', label: 'Shell' },
  ],
  

};

// 本地状态接口，用于兼容现有UI
interface LocalProblem {
  id: string;
  problemId: string;
  title: string;
  difficulty: '简单' | '中等' | '困难';
  status: '通过' | '未通过' | '未尝试';
  passRate: string;
  category: string;
  tags: Array<{
    id?: number;
    name: string;
    color: string;
    oj: string;
    gid: number;
    tcid?: number;
  }>;
  problemCount?: {
    id: number;
    pid: string;
    ac: number;
    ce: number;
    wa: number;
    re: number;
    tle: number;
    mle: number;
    total: number;
    se: number;
  };
}

const ProblemsPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 筛选状态（类似Vue的v-model）
  const [filters, setFilters] = useState({
    activeTab: 'all',
    searchText: '',
    tagFilter: '',
    difficultyFilter: '',
    statusFilter: '',
    currentPage: 1,
    pageSize: 10
  });
  
  const [loading, setLoading] = useState(false);
  const [problems, setProblems] = useState<LocalProblem[]>([]);
  const [total, setTotal] = useState(0);

  // 类似Vue的v-model处理函数
  const handleFilterChange = useCallback((field: string, value: any) => {
    setFilters(prev => ({ ...prev, [field]: value, currentPage: 1 }));
  }, []);

  // 将API数据转换为本地格式的辅助函数
  const convertApiToLocalProblem = useCallback((apiProblem: ProblemListItem): LocalProblem => {
    const calculatePassRate = (problemCount: any) => {
      if (!problemCount || problemCount.total === 0) {
        return '0.0%';
      }
      const passRate = (problemCount.ac / problemCount.total) * 100;
      return `${passRate.toFixed(1)}%`;
    };

    return {
      id: apiProblem.id,
      problemId: apiProblem.problemId || apiProblem.id,
      title: apiProblem.title,
      difficulty: (CONSTANTS.DIFFICULTY_MAP as Record<number, string>)[apiProblem.difficulty] as '简单' | '中等' | '困难' || '简单',
      status: (CONSTANTS.STATUS_MAP as Record<number, string>)[apiProblem.type] as '通过' | '未通过' | '未尝试' || '未尝试', 
      passRate: calculatePassRate(apiProblem.problemCount),
      category: apiProblem.tags?.[0]?.name || '其他',
      tags: apiProblem.tags || [],
      problemCount: apiProblem.problemCount || undefined
    };
  }, []);

  // 获取题目列表（包含筛选逻辑）
  const fetchProblems = useCallback(async () => {
    try {
      setLoading(true);
      const requestParams: ProblemListRequest = {
        page: filters.currentPage,
        size: filters.pageSize,
        isAsc: true,
      };
      
      // 添加难度筛选
      if (filters.difficultyFilter && filters.difficultyFilter !== 'null' && filters.difficultyFilter !== '') {
        requestParams.difficulty = Number(filters.difficultyFilter);
      }
      
      // 添加状态筛选
      if (filters.statusFilter && filters.statusFilter !== 'null' && filters.statusFilter !== '') {
        requestParams.status = Number(filters.statusFilter);
      }
      
      // 添加搜索关键词
      if (filters.searchText) {
        requestParams.keyword = filters.searchText;
      }
      
      // 添加标签筛选
      if (filters.tagFilter && filters.tagFilter !== 'null' && filters.tagFilter !== '') {
        const tagIdMap: Record<string, number[]> = {
          'C语言': [1],
          'C++': [2],
          '数据结构': [3],
          '算法': [4],
          '数据库': [5],
          'Shell': [6]
        };
        requestParams.tagId = tagIdMap[filters.tagFilter];
      }
      
      // 添加标签页筛选
      if (filters.activeTab && filters.activeTab !== 'all') {
        const tabTagIdMap: Record<string, number[]> = {
          'c': [1],
          'cpp': [2],
          'data-structure': [3],
          'algorithm': [4],
          'database': [5],
          'shell': [6]
        };
        requestParams.tagId = tabTagIdMap[filters.activeTab];
      }
      
      console.log('发送请求参数:', requestParams);
      const response = await problemListApi.getProblemList(requestParams);
      
      if (response.code === 200) {
        const apiProblems = response.data.list || [];
        const localProblems = apiProblems.map(convertApiToLocalProblem);
        setProblems(localProblems);
        setTotal(parseInt(response.data.total) || 0);
      } else {
        message.error(response.message || '获取题目列表失败');
      }
    } catch (error: any) {
      console.log('请求错误详情:', error);
      message.error(error.message || '获取题目列表失败');
    } finally {
      setLoading(false);
    }
  }, [filters, convertApiToLocalProblem]);

  // 组件挂载时获取数据
  useEffect(() => {
    fetchProblems();
  }, [fetchProblems]);

  // 监听筛选条件变化
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchProblems();
    }, 300);
    return () => clearTimeout(timer);
  }, [filters.searchText, filters.difficultyFilter, filters.statusFilter, filters.tagFilter, filters.activeTab]);

  // 获取状态图标和颜色
  const getStatusIcon = useCallback((status: string) => {
    const iconMap = {
      '通过': <CheckCircleOutlined style={{ color: '#52c41a' }} />,
      '未通过': <CloseCircleOutlined style={{ color: '#ff4d4f' }} />,
      '未尝试': <MinusCircleOutlined style={{ color: '#faad14' }} />
    };
    return iconMap[status as keyof typeof iconMap] || null;
  }, []);

  // 获取难度颜色
  const getDifficultyColor = useCallback((difficulty: string) => {
    const colorMap = {
      '简单': 'green',
      '中等': 'orange',
      '困难': 'red'
    };
    return colorMap[difficulty as keyof typeof colorMap] || 'default';
  }, []);

  // 计算统计信息百分比
  const calculateStatsPercentages = useCallback((problemCount: any) => {
    if (!problemCount || problemCount.total === 0) {
      return {
        ac: '0.0%',
        wa: '0.0%',
        re: '0.0%',
        ce: '0.0%',
        tle: '0.0%',
        mle: '0.0%',
        se: '0.0%'
      };
    }
    
    const total = problemCount.total;
    return {
      ac: `${((problemCount.ac / total) * 100).toFixed(1)}%`,
      wa: `${((problemCount.wa / total) * 100).toFixed(1)}%`,
      re: `${((problemCount.re / total) * 100).toFixed(1)}%`,
      ce: `${((problemCount.ce / total) * 100).toFixed(1)}%`,
      tle: `${((problemCount.tle / total) * 100).toFixed(1)}%`,
      mle: `${((problemCount.mle / total) * 100).toFixed(1)}%`,
      se: `${((problemCount.se / total) * 100).toFixed(1)}%`
    };
  }, []);

     // 表格列定义
   const columns = useMemo(() => [
     {
       title: '状态',
       dataIndex: 'status',
       key: 'status',
       width: 100,
       render: (status: string) => (
         <Space>
           {getStatusIcon(status)}
           <span>{status}</span>
         </Space>
       ),
     },
           {
        title: '题目',
        dataIndex: 'title',
        key: 'title',
        render: (title: string, record: LocalProblem) => {
          const stats = calculateStatsPercentages(record.problemCount);
          const tooltipContent = record.problemCount ? (
            <div style={{ fontSize: '12px' }}>
              <div>总提交: {record.problemCount.total}</div>
              <div style={{ color: '#52c41a' }}>通过 (AC): {record.problemCount.ac} ({stats.ac})</div>
              <div style={{ color: '#ff4d4f' }}>答案错误 (WA): {record.problemCount.wa} ({stats.wa})</div>
              <div style={{ color: '#faad14' }}>运行时错误 (RE): {record.problemCount.re} ({stats.re})</div>
              <div style={{ color: '#722ed1' }}>编译错误 (CE): {record.problemCount.ce} ({stats.ce})</div>
              <div style={{ color: '#eb2f96' }}>时间超限 (TLE): {record.problemCount.tle} ({stats.tle})</div>
              <div style={{ color: '#13c2c2' }}>内存超限 (MLE): {record.problemCount.mle} ({stats.mle})</div>
              <div style={{ color: '#fa8c16' }}>系统错误 (SE): {record.problemCount.se} ({stats.se})</div>
            </div>
          ) : (
            <div>暂无统计数据</div>
          );

          return (
            <Tooltip 
              title={tooltipContent}
              placement="right"
              overlayStyle={{ maxWidth: '300px' }}
            >
              <a 
                onClick={() => navigate(`/problems/${record.problemId}`)}
                style={{ color: '#1890ff' }}
              >
                {record.id}. {title}
              </a>
            </Tooltip>
          );
        },
      },
     {
       title: '标签',
       dataIndex: 'tags',
       key: 'tags',
       width: 350,
       render: (tags: any[]) => (
         <Space size="small" wrap>
           {tags && tags.length > 0 ? (
             tags.map((tag, index) => (
               <Tag 
                 key={tag.id || index} 
                 color={tag.color}
                 style={{ margin: 0 }}
               >
                 {tag.name}
               </Tag>
             ))
           ) : (
             <span style={{ color: '#999' }}>无标签</span>
           )}
         </Space>
       ),
     },
     {
       title: '难度',
       dataIndex: 'difficulty',
       key: 'difficulty',
       width: 100,
       render: (difficulty: string) => (
         <Tag color={getDifficultyColor(difficulty)}>
           {difficulty}
         </Tag>
       ),
     },
     {
       title: '通过率',
       dataIndex: 'passRate',
       key: 'passRate',
       width: 100,
       render: (passRate: string) => (
         <span style={{ color: '#666' }}>{passRate}</span>
       ),
     },
     ], [getStatusIcon, getDifficultyColor, navigate, calculateStatsPercentages]);

  return (
    <div className="problems-page">
      <div className="problems-container">
        {/* 头部区域 */}
        <div className="problems-header">
          <Title level={2} className="problems-title">题目列表</Title>
          <Button type="primary" size="large" className="start-practice-btn">
            开始做题
          </Button>
        </div>

        {/* 标签页 */}
        <div className="problems-tabs">
          <Tabs
            activeKey={filters.activeTab}
            onChange={(value) => handleFilterChange('activeTab', value)}
            items={CONSTANTS.TAB_ITEMS}
            className="category-tabs"
          />
        </div>

        {/* 筛选和搜索区域 */}
        <div className="problems-filters">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%' }}>
            <Space size="middle">
              <Select
                placeholder="标签"
                style={{ width: 120 }}
                value={filters.tagFilter || undefined}
                onChange={(value) => handleFilterChange('tagFilter', value)}
                allowClear
              >
                <Option value="">全部</Option>
                <Option value="C语言">C语言</Option>
                <Option value="C++">C++</Option>
                <Option value="数据结构">数据结构</Option>
                <Option value="算法">算法</Option>
                <Option value="数据库">数据库</Option>
                <Option value="Shell">Shell</Option>
              </Select>
              
              <Select
                placeholder="难度"
                style={{ width: 120 }}
                value={filters.difficultyFilter || undefined}
                onChange={(value) => handleFilterChange('difficultyFilter', value)}
                allowClear
              >
                <Option value="">全部</Option>
                <Option value="1">简单</Option>
                <Option value="2">中等</Option>
                <Option value="3">困难</Option>
              </Select>
              
              <Select
                placeholder="状态"
                style={{ width: 120 }}
                value={filters.statusFilter || undefined}
                onChange={(value) => handleFilterChange('statusFilter', value)}
                allowClear
              >
                <Option value="">全部</Option>
                <Option value="1">通过</Option>
                <Option value="-1">未通过</Option>
                <Option value="0">未尝试</Option>
              </Select>
            </Space>
            
            <Input
              placeholder="搜索题目..."
              prefix={<SearchOutlined />}
              value={filters.searchText}
              onChange={(e) => handleFilterChange('searchText', e.target.value)}
              style={{ width: 300 }}
              allowClear
            />
          </div>
        </div>

        {/* 题目表格 */}
        <div className="problems-table">
          <Spin spinning={loading}>
            <Table
              columns={columns}
              dataSource={problems}
              pagination={false}
              rowKey="id"
              className="problems-table-content"
            />
          </Spin>
        </div>

        {/* 分页 */}
        <div className="problems-pagination">
          <Pagination
            current={filters.currentPage}
            pageSize={filters.pageSize}
            total={total}
            onChange={(page, size) => handleFilterChange('currentPage', page)}
            showSizeChanger={false}
            showQuickJumper
            showTotal={(total) => `共 ${total} 道题目`}
          />
        </div>
      </div>
    </div>
  );
};

export default ProblemsPage;